package com.itheima.restkeeper.strategy.impl;

import com.itheima.restkeeper.constant.TradingConstant;
import com.itheima.restkeeper.enums.OrderEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Order;
import com.itheima.restkeeper.req.OrderVo;
import com.itheima.restkeeper.req.TradingVo;
import com.itheima.restkeeper.service.IOrderService;
import com.itheima.restkeeper.strategy.TradingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Description:
 * @Version: V1.0
 */
@Component("fkTradingStrategy")
public class FkTradingStrategy implements TradingStrategy {

    @Autowired
    private IOrderService orderService;

    @Override
    public TradingVo convertorTradingVo(OrderVo orderVo) {
        Order order = orderService.getById(orderVo.getId());
        //应付总金额
        BigDecimal payableAmountSum = order.getPayableAmountSum();
        //打折
        BigDecimal discount = orderVo.getDiscount();
        //优惠
        BigDecimal reduce = orderVo.getReduce();
        //计算实付总金额
        BigDecimal realAmountSum = payableAmountSum
                .multiply(discount.divide(new BigDecimal(10)))
                .subtract(reduce);
        //实付金额
        order.setRealAmountSum(realAmountSum);
        //收银人id
        order.setCashierId(orderVo.getCashierId());
        //收银人名称
        order.setCashierName(orderVo.getCashierName());
        //支付渠道
        order.setTradingChannel(orderVo.getTradingChannel());
        //支付类型
        order.setTradingType(orderVo.getTradingType());
        //订单状态：现金结算：YJS,支付宝，微信结算：FKZ
        if (TradingConstant.TRADING_CHANNEL_CASH_PAY.equals(orderVo.getTradingChannel())) {
            order.setOrderState(TradingConstant.YJS);
        } else {
            order.setOrderState(TradingConstant.FKZ);
        }
        boolean flag = orderService.updateById(order);
        //构建交易单
        if (flag) {
            // tradingOrderNo 不要创建
            TradingVo tradingVo = TradingVo.builder()
                    .tradingAmount(realAmountSum)  //实付金额
                    .tradingChannel(orderVo.getTradingChannel())//支付渠道***
                    .tradingType(orderVo.getTradingType())//支付类型
                    .tradingState(order.getOrderState())//交易状态
                    .enterpriseId(order.getEnterpriseId())//商户号***
                    .isRefund(order.getIsRefund()) //是否有退款
                    .storeId(order.getStoreId())  // 门店id
                    .payeeId(orderVo.getCashierId())
                    .payeeName(orderVo.getCashierName())
                    .productOrderNo(order.getOrderNo()) // 订单编号【分库】
                    .memo(order.getTableName() + ":" + order.getOrderNo()) // 备注
                    .build();
            return tradingVo;
        } else {
            throw new ProjectException(OrderEnum.UPDATE_FAIL);
        }
    }
}
